<style lang="scss">
.cus-grid-control {
  .table-actions-wrap {
    display: flex;
    align-items: center;
  }
}
.cus-grid-control__control-btn {
  margin-bottom: 10px;
}
</style>

<template>
<div class="cus-grid-control">
<!--  <div class="a-space-mb-15">-->
<!--    <el-button @click="appendGridItem">添加一个ITEM</el-button>-->
<!--  </div>-->
  <div class="a-space-mb-10">
    <el-radio-group v-model="model.state.flow" @change="onFieldChange('flow', $event)">
      <el-radio-button label="row">row</el-radio-button>
      <el-radio-button label="column">column</el-radio-button>
    </el-radio-group>
  </div>
  <div class="a-space-mb-10">
    <el-radio-group v-model="model.state.flexWrap" @change="onFieldChange('flow', $event)">
      <el-radio-button label="wrap">wrap</el-radio-button>
      <el-radio-button label="nowrap">nowrap</el-radio-button>
    </el-radio-group>
  </div>
  <div class="a-space-mb-10">24分栏</div>
  <div class="a-space-mb-10">
    <el-button class="cus-grid-control__control-btn"
               v-for="control in model.state.controls"
               @click="quickSetLayout(control, 1)">{{control.join(':')}}</el-button>
<!--    <el-button class="cus-grid-control__control-btn" @click="quickSetLayout([6, 18], 2)">8:8:8</el-button>-->
<!--    <el-button class="cus-grid-control__control-btn" @click="quickSetLayout([18, 6], 2)">8:8:8</el-button>-->
<!--    <el-button class="cus-grid-control__control-btn" @click="quickSetLayout([8,8,8], 2)">8:8:8</el-button>-->
<!--    <el-button class="cus-grid-control__control-btn" @click="quickSetLayout([6,12,6], 2)">8:8:8</el-button>-->
<!--    <el-button class="cus-grid-control__control-btn" @click="quickSetLayout([6,6,6,6], 3)">6:6:6:6</el-button>-->
  </div>
  <div class="a-space-mb-10">
    <z-drag-table
        :ref="tableRef"
        :actions="model.control.actions"
        :value="model.state.layouts"
          :column="model.control.column"
          @val-change="onTableChange"
    ></z-drag-table>
  </div>
  <z-cell-item label="列间距" label-width="60px">
    <el-row>
      <el-input style="width: 180px" type="number"  v-model="model.state.columnGap" @change="onFieldChange('columnGap', $event)">

      </el-input> px
    </el-row>
  </z-cell-item>
  <z-cell-item label="行间距" label-width="60px">
    <el-row>
      <el-input style="width: 180px" type="number"  v-model="model.state.rowGap" @change="onFieldChange('rowGap', $event)">

      </el-input> px
    </el-row>
  </z-cell-item>
<!--  <div>-->
<!--    <el-button @click="appendLayout">添加</el-button>-->
<!--  </div>-->
  <div class="a-space-mb-10">
    <h3>控制</h3>
  </div>
  <div class="a-space-mb-10">
    <el-button @click="getGridCtx">添加grid item</el-button>
  </div>
</div>
</template>

<script>
import {CustomRenderControlMixin, defineCustomRender} from "@/plugins/form-render/utils/index.js";
import {inject, nextTick, resolveComponent} from "vue";
import ZDragTable from "@/plugins/z-table/FreeTable/table2.vue";
import ZCellItem from "@/plugins/z-frame/components/ZCellItem.vue";

CustomVueComponent.registerOnce({
  name: 'GridControlInput',
  template: `<div><el-input type="number" min="0" @change="onChange" v-model="val"></el-input></div>`,
  props: {
    value: null
  },
  data() {
    return {
      val: this.value
    }
  },
  methods: {
    onChange(v) {
      // console.log('onChange', v)
      this.$emit('val-change', v)
    }
  }
})

export default {
  name: 'CusGridControl',
  components: {ZCellItem, ZDragTable},
  mixins: [
    CustomRenderControlMixin
  ],
  setup(props, ctx) {
    let ZDragxmlInstance = inject('ZDragxmlInstance')
    let locks = true
    let cached = null
    let JSON5 = ZY.JSON5
    let { data, widgetConfig2, methods, init, buildGetRef, getRef } = defineCustomRender(props, ctx, {
      handleValueInit(newVal) {
        // console.log('handleValueInit', newVal, typeof newVal)
        if (typeof newVal !== 'undefined') {
          try {
            cached = JSON5.parse(newVal)
            console.log('cached', model)
            Object.entries(cached).forEach(([key, value]) => {
              model.state[key] = cached[key]
            })
          } catch (e) {
            console.error(new Error('json parse err', {
              cause: e
            }))
          }
        }
        return newVal
      }
    })
    let tableRef = buildGetRef('table')
    let model =data({
      state: {
        flow: '',
        controls: [
          [12,12],
          [6, 18],
          [18, 6],
          [8,8,8],
          [6,12,6],
          [6,6,6,6],
        ],
        layouts: [
          // {
          //   label: '1',
          //   value: 'sdsd'
          // },
          // {
          //   label: '2',
          //   value: 'sdsd'
          // }
        ]
      },
      control: {
        column: [
          { label: '序号', prop: 'label', INDEX: true, width: '60px' },
          {
            label: '值', prop: 'value',
            render(h, props) {
              // console.log(props.scope.row)
              let row = props.scope.row
              // console.log(props.scope.column.property)
              let input = resolveComponent('GridControlInput')
              return h(input, {
                value: row.value,
                onValChange(v) {
                  row.value = globalThis.ZY2.helpers.parseFloat(v)

                  // console.log(row.value)
                  nextTick(() => {
                    onFieldChange()
                  })
                }
              })
            }
          },
        ],
        actions: [
          // {
          //   label: '删除',
          //   on: {
          //     click(scope) {
          //       // console.log(scope.row,    model.state.layouts)
          //       getRef('table').remove(scope.row)
          //       // model.state.layouts
          //     }
          //   },
          //   attrs: {
          //     type: 'danger'
          //   },
          // },
          {
            label: `<svg style="display: block"
 viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5910" width="16" height="16"><path d="M0 288l1024 0 0 64-1024 0 0-64Z" p-id="5911"></path><path d="M0 480l1024 0 0 64-1024 0 0-64Z" p-id="5912"></path><path d="M0 672l1024 0 0 64-1024 0 0-64Z" p-id="5913"></path></svg>
`,
            attrs:  {
              class: 'z-drag-table__handle',
              style: 'padding-top: 0; padding-bottom: 0;',
              type: ''
            }
          }
        ]
      }
    })

    init(props);

    /**
     *
     */
    function appendGridItem() {
      if (widgetConfig2.dragGridUUID) {
        let instance = ZDragxmlInstance.get(widgetConfig2.dragGridUUID);
        instance.appendStateDom()
      }
    }

    /**
     * 当field改变时
     * @private
     */
    function onFieldChange() {
      let ret = JSON5.stringify(model.state)
      methods.onChange(ret)
    }

    /**
     * 当table改变时 （顺序）
     * @param e
     */
    function onTableChange(e) {
      // console.log('onTableChange',model)
      // model.state.layouts = toRaw(e)
      model.state.layouts = []
      e.forEach((item, index) => {
        model.state.layouts[index] = item
      })
      nextTick(() => {
        onFieldChange()
      })
    }

    /**
     *
     * @private
     * @param value
     * @returns {{id: *, label: *, value: number}}
     */
    function private_struct(value = 0) {
      return   {
        id: ZY.rid(),
        label: ZY.rid(6),
        value: value
      }
    }

    /**
     * 添加一个layout item
     */
    function appendLayout() {
      getRef('table').concat(
          [
            private_struct()
          ]
      )
    }

    /**
     * 快速设置table
     * @param arr
     */
    function quickSetLayout(arr = []) {
      let layouts =  arr.map(v => {
        return private_struct(v)
      })
      getRef('table').setVal(
          layouts
      )
    }

    function getGridCtx() {
      let ctx = ZDragxmlInstance.getRegisterCtx(widgetConfig2?.ctxUUID);
      // console.log(ctx)
      if (ctx) {
        if (ctx.appendColumn) {
          ctx.appendColumn()
        }
      }
    }

    return {
      appendGridItem,
      widgetConfig: widgetConfig2,
      getGridCtx,
      onFieldChange,
      appendLayout,
      tableRef,
      onTableChange,
      quickSetLayout,
      model,
    }
  }
}
</script>
